/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DataAccess;

import entity.House;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.*;

/**
 *
 * @author Mr-Quick
 */
public class HouseDA extends AbstractDataAccess<entity.House> {

    public HouseDA(EntityManager em) {
        super(House.class, em);
    }

    public List<entity.House> search(Date datefrom,
            Date dateto,
            String homestyle,
            String typehouse,
            String city,
            String location,
            int pricefrom,
            int priceto) {
        
        Calendar c = Calendar.getInstance();
        c.setTime(datefrom);
        c.add(Calendar.DATE, -1);
        
        datefrom = c.getTime();
        
        c.setTime(dateto);
        c.add(Calendar.DATE, 1);
        
        dateto = c.getTime();
        
        List<entity.House> results;
        CriteriaBuilder cb;
        CriteriaQuery<entity.House> cq;
        Root root;
        Predicate predicate;
        Order order;

        //Create CriteraBuilder
        cb = getEntityManager().getCriteriaBuilder();
        //Create CriteraQuery
        cq = cb.createQuery(entity.House.class);
        //Create results
        results = new ArrayList<House>();
        //Create root
        root = cq.from(entity.House.class);
        //Create Predicate
        List<Predicate> predicates = new ArrayList<Predicate>();
        predicates.add(cb.between(root.get("dateUp"), datefrom, dateto));
        predicates.add(cb.equal(root.get("homestyle"), homestyle));
        predicates.add(cb.equal(root.get("typehouse"), typehouse));
        predicates.add(cb.like(root.get("city"), "%" + city + "%"));
        predicates.add(cb.like(root.get("location"), "%" + location + "%"));
        predicates.add(cb.between(root.get("deposit"), pricefrom, priceto));
        
        predicate = cb.and(predicates.toArray(new Predicate[predicates.size()]));
        //Create Order
        order = cb.desc(root.get("dateUp"));

        cq.select(root).where(predicate).orderBy(order);
        
        Query q = getEntityManager().createQuery(cq);

        results.addAll(q.getResultList());

        return results;
    }
}
